import React, { Component } from 'react';
import { Button, Modal, message } from 'antd';
import Cropper from 'react-cropper';
import avatar from './img/user-head.png';
import 'cropperjs/dist/cropper.css';
import './styles.less';

let FILE_TYPES = ['image/jpg', 'image/png', 'image/jpeg', 'image/bmp'];
let ImageUrl = '';
class CropperDemo extends Component {
  constructor(props) {
    super(props);
    this.state = {
      src: '',
      refresh: true,
      orginPicture: true,
      // visible: this.props.visible,
    };
    this.confirmUpload = this.confirmUpload.bind(this);
    this.onCancel = this.onCancel.bind(this);
    this.uploadOnClick = this.uploadOnClick.bind(this);
    this.onChange = this.onChange.bind(this);
    // ImageUrl = this.props.src;
  }

  componentDidMount() {
    this.initImage(this.props.src);
  }

  componentWillReceiveProps(nextProps) {
    if (this.props.src !== nextProps.src) {
      this.initImage(nextProps.src);
    }
  }

  // 图片无法加载时，使用默认图片
  imgExists = e => {
    // 默认图片
    const imgUrl = avatar;
    if (imgUrl) {
      e.target.src = imgUrl;
      e.target.title = '加载失败';
    }
  };

  initImage = imgUrl => {
    ImageUrl = imgUrl;
    this.setState({
      refresh: true,
    });
  };

  onChange = e => {
    e.preventDefault();
    let files = {};
    if (e.dataTransfer != null) {
      files = e.dataTransfer.files;
    } else if (e.target != null) {
      files = e.target.files;
    }

    if (files.length > 0) {
      // 验证 files[0] 信息的文件大小
      const fileMaxSize = 1024;
      const fileSize = files[0].size / 1024;
      if (fileSize > fileMaxSize) {
        message.warn('文件不能大于1M！');
      } else if (fileSize <= 0) {
        message.warn('文件不能为0');
      }
      // 验证 files 信息的文件类型
      const fileType = files[0].type;
      FILE_TYPES = this.props.FILE_TYPES ? this.props.FILE_TYPES : FILE_TYPES;
      if (!FILE_TYPES.includes(fileType)) {
        message.warn('不接受此文件类型');
        return false;
      }

      const reader = new FileReader();
      reader.onload = () => {
        ImageUrl = reader.result;
        this.setState({
          refresh: true,
          orginPicture: false,
        });
      };
      reader.readAsDataURL(files[0]);
    } else {
      if (this.state.src === null) {
        message.warn('请选择文件');
      }
      return false;
    }
    return false;
  };

  circleImage = (img, oldImgWidth, oldImgHeight) => {
    let width;
    let height;
    if (img.width > img.height) {
      width = img.height;
      height = img.height;
    } else {
      width = img.width;
      height = img.width;
    }
    const canvas = document.createElement('canvas');
    if (!canvas.getContext) {
      // 判断浏览器是否支持canvas，如果不支持在此处做相应的提示
      message.warn('您的浏览器版本过低，暂不支持。');
      return false;
    }
    canvas.width = width;
    canvas.height = height;
    const contex = canvas.getContext('2d');
    const circle = {
      x: width / 2,
      y: height / 2,
      r: width / 2,
    };
    contex.clearRect(0, 0, width, height);
    contex.save();
    contex.beginPath();
    contex.arc(circle.x, circle.y, circle.r, 0, Math.PI * 2, false);
    contex.clip();
    contex.drawImage(img, 0, 0, oldImgWidth, oldImgHeight, 0, 0, width, height);
    contex.restore();
    return canvas.toDataURL();
  };

  uploadImg = () => {
    if (this.state.src === null) {
      message.warn('请选择图片');
      return 0;
    }
    const croppedCanvas = this.cropper.getCroppedCanvas({
      minWidth: 200,
      minHeight: 200,
      width: 200,
      height: 200,
      maxWidth: 200,
      maxHeight: 200,
    });

    if (typeof croppedCanvas === 'undefined') {
      return 0;
    }
    const img = new Image();
    img.src = croppedCanvas.toDataURL();

    img.onload = () => {
      const base64 = this.circleImage(img, img.width, img.height);
      const file = {
        base64,
      };
      // this.setState({
      //   src: base64,
      // });
      if (this.props.getImageInfo) {
        this.props.getImageInfo(file);
      }
    };
    return 0;
  };

  onCancel = () => {
    this.inputImage.value = '';
    this.props.close();
    this.setState({ orginPicture: true });
  };

  confirmUpload = () => {
    this.uploadImg();
    this.props.close();
    this.inputImage.value = '';
    this.setState({ orginPicture: true });
  };

  uploadOnClick = () => {
    if (this.props.dispatchMethod) {
      this.props.dispatchMethod(false);
    }

    if (!this.props.disabled) {
      document.form.picpath.click();
    }
  };

  render() {
    return (
      <div>
        <Modal
          visible={this.props.visible}
          onOk={this.confirmUpload}
          onCancel={this.onCancel}
          okText="确认"
          cancelText="取消"
          width={450}
          closable={false}
          destroyOnClose
        >
          <form name="form">
            <input
              type="file"
              name="picpath"
              id="picpath"
              hidden={this.state.refresh}
              accept="image/*"
              onChange={this.onChange}
              ref={input => {
                this.inputImage = input;
              }}
            />
            <Button onClick={this.uploadOnClick} style={{ marginBottom: '8px' }}>
              {this.props.buttonTitle ? this.props.buttonTitle : '点击更新头像'}
            </Button>
          </form>
          {this.state.orginPicture ? (
            <div style={{ textAlign: 'center' }}>
              <img
                src={ImageUrl}
                alt="原始图片"
                title="原始图片"
                onError={this.imgExists.bind(this)}
              />
            </div>
          ) : (
            <Cropper
              hidden
              style={{ height: 300, width: 400 }}
              aspectRatio={1}
              // preview=".uploadCrop"
              guides={false}
              src={ImageUrl}
              ref={cropper => {
                this.cropper = cropper;
              }}
            />
          )}
        </Modal>
      </div>
    );
  }
}
export default CropperDemo;
